function selectedIndex = tournamentSelection(fitnessValues, tournamentSize)
    % Performs tournament selection
    populationSize = length(fitnessValues);
    if populationSize == 0
        error('Cannot perform tournament selection on empty population.');
    end
    
    numParticipants = min(tournamentSize, populationSize);
    
    % Select participants randomly without replacement
    participantIndices = datasample(1:populationSize, numParticipants, 'Replace', false);
    
    % Find the best among participants
    [~, winnerLocalIndex] = max(fitnessValues(participantIndices));
    selectedIndex = participantIndices(winnerLocalIndex);
end